package se.jocke.nbrs.service.impl;

import java.awt.EventQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import org.openide.util.RequestProcessor;
import org.openide.util.lookup.ServiceProvider;
import se.jocke.nbrs.service.EventBus;

/**
 *
 * @author jocke
 */
@ServiceProvider(service = EventBus.class)
public class EventBusImpl implements EventBus {

    private static final com.google.common.eventbus.EventBus EVENT_BUS = new com.google.common.eventbus.EventBus();

    private static final Logger LOG = Logger.getLogger(EventBusImpl.class.getName());

    @Override
    public void post(Object event) {
        EVENT_BUS.post(event);
        LOG.info("Posting message");
    }

    @Override
    public void register(Object object) {
        LOG.log(Level.INFO, "Register {0}", object);
        EVENT_BUS.register(object);
    }

    @Override
    public void unregister(Object object) {
        LOG.log(Level.INFO, "unregister {0}", object);
        EVENT_BUS.unregister(object);
    }

    @Override
    public void postAsync(final Object event) {
        if (SwingUtilities.isEventDispatchThread()) {
            RequestProcessor.getDefault().execute(new Runnable() {
                @Override
                public void run() {
                    EVENT_BUS.post(event);
                }
            });

        } else {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    EVENT_BUS.post(event);
                }
            });
        }
    }

}
